#include "download_file.h"

#include "server_define.h"

download_file::download_file(QObject *parent) : QObject{parent} {

}

void download_file::startListen(unsigned short port) {
    if (mysql == nullptr) {
        mysql = new sql;
        mysql->connect(MYSQL_SERVER_HOST, MYSQL_SERVER_PORT, MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_DB_NAME);
    }

    //分配内存空间
    fileserver = new QTcpServer(this);
    fileserver->listen(QHostAddress::Any, port);
    connect(fileserver, &QTcpServer::newConnection, [=]() {
        //取出建立好连接的套接字
        filesocket = fileserver->nextPendingConnection();

        isStart = true;
        connect(filesocket, &QTcpSocket::readyRead, this, &download_file::recvFile);
        connect(filesocket, &QTcpSocket::disconnected, this, [=]() {
            qDebug() << "disconnected";
            //断开连接
            filesocket->close();
            filesocket->deleteLater();
            emit recvOver();
        });
    });
}

void download_file::recvFile() {
    //取出接收的内容
    QByteArray buf = filesocket->readAll();
    static QString username;
    if(isStart) {
        //接收头部
        isStart = false;
        //解析头部
        filename = QString(buf).section("##", 0, 0);
        filesize = QString(buf).section("##", 1, 1).toInt();
        username = QString(buf).section("##", 2, 2);
        if (filesize == 0) {
            isStart = true;
            file.close();
            return;
        }
        recvfilesize = 0;
        //打开文件
        file.setFileName(FILE_SAVE_PATH + filename);
        qDebug() << username << " " << filename << " " << filesize;
        bool isOk = file.open(QIODevice::WriteOnly);
        if(!isOk) {
            file.close();
            isStart = true;
            return;
        }
    } else {
        qint64 len = file.write(buf);
        if (len > 0) {
            recvfilesize += len;//累计接收大小
        }
        // qDebug() << len << " " << recvfilesize << filesize;
        // qDebug() << abs(recvfilesize) << " " << abs(filesize) << '\n';
        if(abs(recvfilesize) == abs(filesize)) {
            file.close();
            isStart = true;
            if (filename.endsWith(".mp3")) {
                mysql->insert_song(filename, FILE_SAVE_PATH + filename);
                mysql->insert_user_song(username, filename);
            } else if (filename.endsWith(".lrc")) {
                mysql->insert_lrc(filename, FILE_SAVE_PATH + filename);
                auto lrc_filename = filename;
                auto mp3_filename = filename.replace(".lrc", ".mp3");
                qDebug() << mp3_filename << " " << lrc_filename;
                mysql->insert_song_lrc(mp3_filename, lrc_filename);
            }
            qDebug() << "rec!!";
        }
    }
}
